<template>
  <div class='page-content'>

    <!-- 工具栏区域 -->
    <table-bar :showTop="false"
               :columns="columns"
               @changeColumn="changeColumn">
      <!-- 条件查询区域 -->
      <div slot="top">
        <el-form :model="queryForm"
                 :rules="queryFormRules"
                 ref="queryFormRef"
                 label-width="100px">
          <el-row :gutter="20">
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24"
                    :sm="12"
                    :lg="7">
              <el-form-item label="记录时间"
                            prop="date">
                <el-date-picker v-model="batchDate"
                                @change="dateChange"
                                value-format="yyyy-MM-dd"
                                type="daterange"
                                range-separator="-"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :xs="24"
                    :sm="12"
                    :lg="6">
              <el-form-item label="屠宰日期"
                            prop="batchDate">
                <el-date-picker v-model="queryForm.batchDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择屠宰日期">
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :xs="24"
                    :sm="12"
                    :lg="6">
              <el-form-item label="经手人"
                            prop="handler">
                <el-input placeholder="请输入经手人姓名

"
                          v-model="queryForm.handler"></el-input>
              </el-form-item>
            </el-col>

            <el-row :xs="24"
                    :sm="12"
                    :lg="6"
                    style="float: right; margin-right: 10px;">
              <el-button type="primary"
                         @click="query">搜索</el-button>
              <el-button @click="resetForm('queryFormRef')">重置</el-button>
            </el-row>
          </el-row>
        </el-form>
      </div>
      <!-- 左侧按钮 -->
      <div slot="bottom">
        <el-button type="primary"
                   plain
                   @click="showAddDialog">新增批次</el-button>
        <el-button type="danger"
                   plain
                   @click="delByIds">批量删除</el-button>
        <el-button type="success"
                   plain>导入</el-button>
        <el-button type="success"
                   plain>导出</el-button>
      </div>

    </table-bar>

    <!-- 表格区域 -->
    <the-table :data="batchList"
               :showPage="false"
               @getDataBySelectBox="handleSelectionChange"
               ref="batchListRef">
      <el-table-column type="selection"
                       width="55"></el-table-column>

      <el-table-column label="序号"
                       type="index"
                       v-if="columns[0].show" />
      <el-table-column label="屠宰批次"
                       prop="shBatch"
                       v-if="columns[1].show" />
      <el-table-column label="屠宰数量"
                       prop="amount"
                       v-if="columns[2].show" />
      <!-- <el-table-column label="养殖批次"
                       prop="farmingBatch"
                       v-if="columns[2].show" /> -->
      <el-table-column label="经手人"
                       prop="handler"
                       v-if="columns[3].show" />
      <el-table-column label="屠宰批次日期"
                       prop="batchDate"
                       v-if="columns[4].show" />
      <!-- <el-table-column label="屠宰流程名"
                       prop="sex"
                       v-if="columns[4].show" /> -->
      <!-- <el-table-column label="屠宰日期"
                       prop="batchDate"
                       v-if="columns[5].show" /> -->
      <el-table-column label="创建时间"
                       prop="gmtCreate"
                       v-if="columns[6].show" />

      <el-table-column label="修改时间"
                       prop="gmtModified"
                       v-if="columns[7].show" />
      <el-table-column label="操作"
                       fixed="right"
                       min-width="180px"
                       v-if="columns[8].show">
        <template slot-scope="scope">
          <el-button type="text"
                     icon="el-icon-document"
                     @click="showDetailsDialog(scope.row)">
            详情
          </el-button>
          <el-button type="text"
                     icon="el-icon-edit"
                     @click="showEditDialog(scope.row)">
            编辑
          </el-button>
          <el-button type="text"
                     style="color: #FA6962"
                     icon="el-icon-delete"
                     @click="delById(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>

    <!-- 分页器区域 -->
    <el-pagination layout="total, sizes, prev, pager, next, jumper"
                   :page-sizes="[5, 8, 10, 15]"
                   :page-size="pageSize"
                   :current-page="pageNum"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   class="page">
    </el-pagination>

    <!-- 批次详情对话框 -->
    <el-dialog :visible.sync="detailsDialog"
               width="30%">
      <div slot="title"
           class="dialog_title">
        <span>批次详细信息</span>
      </div>
      <div>
        <the-table :data="detailsList"
                   :showPage="false">
          <el-table-column label="肉鸽类型"
                           prop="doveCategory" />
          <el-table-column label="数量"
                           prop="ammount" />

          <!-- <el-table-column label="创建时间"
                           prop="gmtCreate" />
          <el-table-column label="修改时间"
                           prop="gmtModified" /> -->

        </the-table>
      </div>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="detailsDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="detailsDialog = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增&修改批次对话框 -->
    <el-dialog :title="isShowAddForm?'新增批次':'修改批次'"
               :visible.sync="addDialog"
               width="60%">
      <el-form ref="addFormRef"
               :model="addForm"
               :rules="addFormRules"
               inline
               label-width="110px">
        <el-form-item label="养殖批次日期"
                      v-if="isShowAddForm"
                      required>
          <el-date-picker v-model="farmingBatchDate"
                          @change="batchDateChange"
                          required
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择养殖批次日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="养殖批次"
                      v-if="isShowAddForm"
                      required>
          <el-select v-model="addForm.AddBatch.farmingBatch"
                     filterable
                     placeholder="请关联所属养殖批次">
            <el-option v-for="item in farmingBatchOptions"
                       :key="item.farmBatch"
                       :label="item.farmBatch"
                       :value="item.farmBatch"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="屠宰日期"
                      v-if="isShowAddForm"
                      required>
          <el-date-picker v-model="addForm.AddBatch.batchDate"
                          required
                          type="datetime"
                          value-format="yyyy/MM/dd HH:mm:ss"
                          placeholder="选择屠宰日期"
                          default-time="12:00:00">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="屠宰流程"
                      v-if="isShowAddForm"
                      required>
          <el-select v-model="addForm.AddBatch.processId"
                     filterable
                     placeholder="请关联屠宰批次">
            <el-option v-for="item in processList"
                       :key="item.shBatchDetailId"
                       :label="item.processId"
                       :value="item.processId">
            </el-option>
            <template>
              <div class="el-selec-tinner">
                <el-input v-model="addForm.AddBatch.processId"></el-input>
              </div>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="经手人"
                      required>
          <el-select v-model="addForm.AddBatch.handler"
                     filterable
                     placeholder="请选择经手人">
            <el-option v-for="item in handlerAddList"
                       :key="item.name"
                       :label="item.name"
                       :value="item.name">
            </el-option>
            <template>
              <div class="el-selec-tinner">
                <el-input v-model="addForm.AddBatch.handler"></el-input>
              </div>
            </template>
          </el-select>
          </el-input>
        </el-form-item>
        <el-divider>批次详情</el-divider>
        <div v-for="(item,index) in addForm.AddBatchInfo"
             :key="index">
          <span class="batch-item">{{index+1}}：</span>
          <el-form-item label="肉鸽类型"
                        required>
            <!-- <el-input v-model="addForm.AddBatchInfo[index].doveCategory"> -->
            <el-select v-model="addForm.AddBatchInfo[index].doveCategory"
                       filterable
                       placeholder="请选择肉鸽类型">
              <el-option v-for="item in doveCategoryAddList"
                         :key="item"
                         :label="item"
                         :value="item">
              </el-option>
              <template>
                <div class="el-selec-tinner">
                  <el-input v-model="addForm.AddBatchInfo[index].doveCategory"></el-input>
                </div>
              </template>
            </el-select>
            </el-input>
          </el-form-item>
          <el-form-item label="屠宰数量"
                        required>
            <el-input v-model="addForm.AddBatchInfo[index].ammount">
            </el-input>
          </el-form-item>
          <el-button icon="el-icon-delete"
                     @click="removeBatchItem(index)">
          </el-button>
        </div>

      </el-form> <span slot="footer"
            class="dialog-footer">
        <el-button @click="AddBatchItem">新增批次详情</el-button>
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <base-choice></base-choice>
  </div>
</template>

<script>
import { changeColumn, pagination, dialogClose, multipleSelection, queryForm } from '@/api/mixin/'
import { dateShorter } from '@/utils/utils'
export default {
  name: "BatchManage",
  meta: {
    title: "屠宰批次管理",
  },
  mixins: [changeColumn, pagination, dialogClose, multipleSelection, queryForm],
  data () {
    return {
      columns: [
        { name: "序号", show: true },
        { name: "屠宰批次", show: false },
        { name: "数量", show: true },
        // { name: "养殖批次", show: true },
        { name: "经手人", show: true },
        { name: "肉鸽类型", show: true },
        { name: "屠宰日期", show: true },
        { name: "创建时间", show: true },
        { name: "修改时间", show: true },
        { name: "操作", show: true },
      ],
      //新增流程对话框
      addDialog: false,
      detailsDialog: false,
      // 批次列表
      batchList: [],
      detailsList: [],//流程详情
      queryForm: {
        // shBatch: '',//屠宰批次
        // farmingBatch: '',//养殖出库批次
        handler: '',//经手人姓名
        begin: '',
        end: '',
        batchDate: '',//屠宰批次日期
      },
      date: [],//日期
      batchDate: [],//屠宰日期
      // 条件查询表单检验规则
      queryFormRules: {
        handler: [],
        doveCategory: [],
      },
      addDialog: false,
      shBatchDetailId: '',//批次id
      addFormRules: {
        doveCategory: [{ required: true, message: '请输入屠宰完肉鸽类型', trigger: 'blur' }, { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }],
        handler: [{ required: true, message: '请输入经手人', trigger: 'blur' }],
        ammount: [{ required: true, message: '请输入屠宰数量', trigger: 'blur' }]
      },
      isShowAddForm: true,
      addForm: {
        //批次详情
        AddBatchInfo: [{
          doveCategory: '',//肉鸽类型
          ammount: '',//屠宰数量
        }],
        AddBatch: {
          handler: '',//经手人ok
          slaId: 0,//屠宰场id
          guige: 0,
          batchDate: '',//屠宰日期ok
          farmingBatch: '',//养殖出库批次ok
          processId: ''

        },
      },
      farmingBatchDate: '',
      farmingBatchOptions: [],//养殖出库批次
      processList: [],//processid
      doveCategoryAddList: [],
      handlerAddList: [{ name: '王1' }, { name: '王2' }, { name: '王3' }, { name: '王4' }]

    }
  },
  computed: {
    select_shId () {
      return this.$store.state.Usersetting.SlaughterInfo.shId
    }
  },
  methods: {
    //展示批次详情对话框
    async showDetailsDialog ({ shBatch }) {


      //根据id获取详细数据
      const { data: res } = await this.$http.get(`/pigeon/t-slaughterhouse-batch/pageBath/${shBatch}/1/100`)
      if (res.statusCode !== 20000) return this.$message.error('获取记录详情失败')


      // res.data 直接是对象

      this.detailsList = res.data

      this.detailsDialog = true
    },

    //分页获取列表
    async getBatchList () {
      const { data: res } = await this.$http.get(`/pigeon/t-slaughterhouse-batch/getPageTO/${this.pageNum}/${this.pageSize}`)
      // console.log(res);
      if (res.statusCode !== 20000) return this.$message.error('获取批次列表失败')

      //保存
      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      dateShorter(res.data.records, 'batchDate')
      this.batchList = res.data.records
      this.total = res.data.total
    },
    // 监听日期选择器变化
    dateChange (val) {
      // 没有选中val = null
      if (!val) {
        this.queryForm.begin = ''
        this.queryForm.end = ''
        return this.getList()
      }
      this.queryForm.begin = val[0]
      this.queryForm.end = val[1]

    },
    // 条件查询
    async query () {
      const { data: res } = await this.$http.get(`/pigeon/t-slaughterhouse-batch-info/getPageToInfo/${this.pageNum}/${this.pageSize}`, { params: this.queryForm })
      if (res.statusCode !== 20000) return this.$message.error('查询失败')

      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      dateShorter(res.data.records, 'batchDate')
      this.batchList = res.data.records
      this.total = res.data.total

    },
    getList () {
      this.getBatchList()
    },

    /* 删除 */
    delById ({ shBatchDetailId }) {
      this.delById_Pigeon('/pigeon/t-slaughterhouse-batch-info/deleteTsById/', shBatchDetailId)
    },
    delByIds () {
      console.log('delByIds');
      this.delByIds_Pigeon('/pigeon/t-slaughterhouse-batch-info/deleteByIds/', 'shBatchDetailId')
    },
    // delByIds_Pigeon方法封装屠宰模块的批量删除，仅屠宰的接口有统一
    /* 删除 */

    /* 编辑 */
    async showEditDialog ({ shBatchDetailId, shBatch }) {
      //保存id
      this.shBatchDetailId = shBatchDetailId
      // this.editForm.shBatch = shBatch
      //获取最新的记录
      const { data: res } = await this.$http.get(`/pigeon/t-slaughterhouse-batch-info/getLaughterById/${shBatchDetailId}`)
      if (res.statusCode !== 20000) return this.$message.error('获取最新批次记录失败')




      //保存
      this.addForm = res.data
      // 显示
      this.isShowAddForm = false
      this.addDialog = true
    },
    update () {
      // 表单验证
      this.$refs.editFormRef.validate(async flag => {
        if (!flag)
          return this.$message.error('请正确填写表单')
        // 发送请求
        const { data: res } = await this.$http.put(`/pigeon/t-slaughterhouse-batch-info/updateTs/${this.shBatchDetailId}`, this.editForm)
        if (res.statusCode !== 20000) return this.$message.error('修改失败')

        //刷选列表
        this.getList()


        // 关闭
        this.editDialog = false
        this.$message.success('修改成功')



      })





    },
    /* 编辑 */


    /* 新增 */
    //展示新增流程对话框
    async showAddDialog () {
      // 获取屠宰场id
      this.addForm.AddBatch.slaId = this.select_shId
      this.addForm.AddBatch.guige = 3 //写死？


      // 获取养殖批次列表
      await this.batchDateChange()

      //获取屠宰流程
      this.getProcessList()

      this.isShowAddForm = true
      this.addDialog = true
    },
    async add () {
      this.$refs.addFormRef.validate(async flag => {
        if (!flag)
          return this.$message.error('请正确填写表单')
        const { data: res } = await this.$http.post(`/pigeon/t-slaughterhouse-batch-info/saveTs/001`, this.addForm)
        if (res.statusCode !== 20000) return this.$message.error('添加失败')

        this.$message.success('添加成功')
        this.getList()
        this.addDialog = false
      })

    },
    //获取养殖批次
    async batchDateChange (date) {
      if (!this.$store.state.Usersetting.BaseInfo.id) { // 养殖批次需要获取养殖基地id
        this.$store.commit('isShowBaseChoice', 'Dovecote')
      }
      const baseId = this.$store.state.Usersetting.BaseInfo.id

      const dateParam = date ? '&date=' + date : ''
      const { data: res } = await this.$http.get(`/breed/shipmentOutBill/getFarmBatchByBaseId?baseId=${baseId}` + dateParam)
      if (res.statusCode !== 20000) return this.$message.error('获取养殖批次失败')
      console.log(res);

      // if (res.data.length === 0)
      //   this.farmingBatchOptions = [{ farmBatch: '数据为空', }]
      this.farmingBatchOptions = res.data
    },
    // 新增批次详情
    AddBatchItem () {
      this.addForm.AddBatchInfo.push({
        doveCategory: '',
        ammount: ''
      })
    },
    removeBatchItem (index) {
      this.addForm.AddBatchInfo.splice(index, 1)
    },
    // 关联流程获取列表
    async getProcessList () {
      const { data: res } = await this.$http.get(`/pigeon/t-slaughterhouse-process/getPageTO/1/50`)

      if (res.statusCode !== 20000) return this.$message.error('获取屠宰流程失败')

      this.processList = res.data.records
    },
    /* 新增 */
    async getdoveCategoryAddList () {
      const { data: res } = await this.$http.get('/pigeon/t-slaughterhouse-batch-info/getAllType')
      if (res.statusCode !== 20000) return this.$message.error('获取肉鸽类型列表失败')
      this.doveCategoryAddList = res.data
    }
  },
  created () {
    this.getBatchList()
    this.getdoveCategoryAddList()
  }
}
</script>

<style lang="scss" scoped>
.page {
  margin-top: 6px;
  text-align: center;
}
.el-date-editor--daterange.el-input,
.el-date-editor--daterange.el-input__inner,
.el-date-editor--timerange.el-input,
.el-date-editor--timerange.el-input__inner {
  width: 100%;
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

// /deep/ .el-divider .el-divider--horizontal {
//   margin: -5px 0 15px;
// }
// 新增批次详情
.batch-item {
  display: inline-block;
  width: 60px;
  margin-right: -30px;
  text-align: right;
}
.el-selec-tinner {
  width: 95%;
}
</style>